<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/1/25
 * Time: 16:05
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Withdraw extends Base
{
    /**
     * 提现列表
     */
    public function index(){
        if(request()->isAjax ()){
            $withdraw_number = trim(input('withdraw_number'), ' '); // 提现单号
            $user_real_name = trim(input('user_real_name'), ' '); // 用户名
            $user_phone = trim(input('user_phone'), ' '); // 手机号
            $start_time = input('start_time');
            $end_time = input('end_time');
            $withdraw_status = input('withdraw_status');
            
            $where = [];
            if(isset($withdraw_number) && $withdraw_number != ''){
                $where['withdraw_number'] = ['like', '%' . $withdraw_number . '%'];
            }
            if(isset($user_real_name) && $user_real_name != ''){
                $where['user_real_name'] = ['like', '%' . $user_real_name . '%'];
            }
            if(isset($user_phone) && $user_phone != ''){
                $where['user_phone'] = ['like', '%' . $user_phone . '%'];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['withdraw_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['withdraw_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['withdraw_time'] = ['<=', $end_time];
            }
            if(isset($withdraw_status) && $withdraw_status != ''){
                $where['withdraw_status'] = $withdraw_status;
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_withdraw')
                ->join('up_u_user', 'withdraw_user_id = user_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $count2 = Db::table('up_withdraw')
                ->join('up_u_user', 'withdraw_user_id = user_id', 'LEFT')
                ->where($where)
                ->column('withdraw_id');
            $lists = Db::table('up_withdraw')
                ->join('up_u_user', 'withdraw_user_id = user_id', 'LEFT')
                ->field('withdraw_id, withdraw_status, withdraw_type, withdraw_number, withdraw_price, withdraw_remark, 
                withdraw_time, user_real_name, user_phone, user_bank_username, user_bank_name, user_bankcard_code, 
                withdraw_inte_id')
                ->where($where)
                ->order('withdraw_time desc')
                ->page($Nowpage,$limits)
                ->select();
            if($lists){
                foreach($lists as $k => $v){
                    if($v['withdraw_type'] == 1){
                        $huokuan_number = Db::table('up_integral_tixian_hk')
                            ->where('zhuan_inte_id', $v['withdraw_inte_id'])
                            ->sum('zhuan_number');
                        $lists[$k]['real_price'] = $v['withdraw_price'] - $huokuan_number;
                    }else{
                        $lists[$k]['real_price'] = 0;
                    }
                }
            }
            $str = '';
            if($count2){
                $str = implode(',', $count2);
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists, 'count2' => $str]);
        }
        return $this->fetch();
    }
    
    /**
     * 提现详情
     * @return mixed
     */
    public function withdrawDetail(){
        $withdraw_id = input('withdraw_id');
        $detail = Db::table('up_withdraw')
            ->join('up_u_user', 'withdraw_user_id = user_id', 'LEFT')
            ->field('withdraw_id, withdraw_status, withdraw_type, withdraw_number, withdraw_price, withdraw_remark, 
                withdraw_time, withdraw_check_time, user_real_name, user_phone, user_bank_username, user_bank_name, 
                user_bankcard_code, withdraw_inte_id')
            ->where('withdraw_id', $withdraw_id)
            ->find();
        if($detail['withdraw_type'] == 1){
            $huo_number = Db::table('up_integral_tixian_hk')->where('zhuan_inte_id', $detail['withdraw_inte_id'])->sum('zhuan_number');
            $detail['real_price'] = $detail['withdraw_price'] - $huo_number;
        }else{
            $detail['real_price'] = 0;
        }
        return $this->fetch('withdraw/withdrawdetail', ['detail' => $detail]);
    }
    
    /**
     * 审核通过
     * @return \think\response\Json
     */
    public function withAllow(){
        $withdraw_id = input('id');
        $withdraw = Db::table('up_withdraw')
            ->where('withdraw_id', $withdraw_id)
            ->field('withdraw_type, withdraw_price, withdraw_user_id')
            ->find();
        
        Db::startTrans();
        try{
            // 修改状态
            $update =[
                'withdraw_status' => 2,
                'withdraw_check_time' => date('Y-m-d H:i:s'),
//                'withdraw_can_zhuan' => 1
            ];
            Db::table('up_withdraw')->where('withdraw_id', $withdraw_id)->update($update);
            
            // 如果是转货款
            if($withdraw['withdraw_type'] == 2){
                $user = Db::table('up_u_user')
                    ->where('user_id', $withdraw['withdraw_user_id'])
                    ->field('user_total_balance, user_first_balance, user_recharge_balance, user_invite_other, user_real_name')
                    ->find();
                // 更新用户其他款项、总积分和可用积分
                Db::table('up_u_user')->where('user_id', $withdraw['withdraw_user_id'])
                    ->update([
                        'user_total_balance' => $user['user_total_balance'] + $withdraw['withdraw_price'],
                        'user_huo_balance' => $user['user_first_balance'] + $withdraw['withdraw_price'],
                        'user_recharge_balance' => $user['user_recharge_balance'] + $withdraw['withdraw_price'],
                    ]);
//                Db::table('up_u_user')->where('user_id', $withdraw['withdraw_user_id'])->setInc('user_total_balance', $withdraw['withdraw_price']);
//                Db::table('up_u_user')->where('user_id', $withdraw['withdraw_user_id'])->setInc('user_other_balance', $withdraw['withdraw_price']);
//                Db::table('up_u_user')->where('user_id', $withdraw['withdraw_user_id'])->setInc('user_recharge_balance', $withdraw['withdraw_price']);
                // 插入积分明细 积分提现转货款
                $integral = [
                    'inte_user_id' => $withdraw['withdraw_user_id'],
                    'inte_other_user_id' => 0,
                    'inte_type' => 1,
                    'inte_des' => '佣金转货款',
                    'inte_number' => $withdraw['withdraw_price'],
                    'inte_front' => $user['user_recharge_balance'],
                    'inte_after' => $user['user_recharge_balance'] + $withdraw['withdraw_price'],
                    'inte_time' => date('Y-m-d H:i:s'),
                    'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT)
                ];
                Db::table('up_integral')->insert($integral);
                
                // 上级和上上级分佣
                //**********  分佣
                if($user['user_invite_other']) {
                    // 上级
                    $up_user = Db::table('up_u_user')->where('user_invite', $user['user_invite_other'])
                        ->field('user_id, user_role, user_fy_balance, user_invite_other, user_total_fy_balance')
                        ->find();
                    if($up_user['user_role'] == 3) { // 货款只有富二代上级和富二代上上级有
                        $up_jia_bl = Db::table('up_fy_config')->where('fy_config_id', 2)->value('fy_config_content');
                        $up_yj = $up_jia_bl / 100 * $withdraw['withdraw_price']; // 佣金数
                        // 上级积分明细
                        $intergral_up = [
                            'inte_user_id' => $up_user['user_id'],
                            'inte_other_user_id' => $withdraw['withdraw_user_id'],
                            'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT),
                            'inte_number' => $up_yj,
                            'inte_front' => $up_user['user_fy_balance'],
                            'inte_after' => $up_user['user_fy_balance'] + $up_yj,
                            'inte_time' => date('Y-m-d H:i:s'),
                            'inte_sort' => 2,
                            'inte_type' => 3,
                            'inte_des' => $user['user_real_name'] . '佣金转货款-佣金'
                        ];
                        Db::table('up_integral')->insert($intergral_up);
            
                        // 上级佣金积分
                        $up_user_yj = [
                            'user_fy_balance' => $up_user['user_fy_balance'] + $up_yj,
                            'user_total_fy_balance' => $up_user['user_total_fy_balance'] + $up_yj
                        ];
                        Db::table('up_u_user')->where('user_id', $up_user['user_id'])->update($up_user_yj);
            
                        // 上上级
                        if($up_user['user_invite_other']) {
                            $up_up_user = Db::table('up_u_user')->where('user_invite', $up_user['user_invite_other'])
                                ->field('user_id, user_role, user_fy_balance, user_invite_other, user_total_fy_balance')
                                ->find();
                            if($up_up_user['user_role'] == 3) {
                                $up_up_jia_bl = Db::table('up_fy_config')->where('fy_config_id', 4)->value('fy_config_content');
                                $up_up_yj = $up_up_jia_bl / 100 * $withdraw['withdraw_price']; // 佣金数
                                // 上上级积分明细
                                $intergral_up_up = [
                                    'inte_user_id' => $up_up_user['user_id'],
                                    'inte_other_user_id' => $withdraw['withdraw_user_id'],
                                    'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT),
                                    'inte_number' => $up_up_yj,
                                    'inte_front' => $up_up_user['user_fy_balance'],
                                    'inte_after' => $up_up_user['user_fy_balance'] + $up_up_yj,
                                    'inte_time' => date('Y-m-d H"i:s'),
                                    'inte_sort' => 3,
                                    'inte_type' => 3,
                                    'inte_des' => $user['user_real_name'] . '佣金转货款-佣金'
                                ];
                                Db::table('up_integral')->insert($intergral_up_up);
                    
                                // 上上级佣金积分
                                $up_up_user_yj = [
                                    'user_fy_balance' => $up_up_user['user_fy_balance'] + $up_up_yj,
                                    'user_total_fy_balance' => $up_up_user['user_total_fy_balance'] + $up_up_yj
                                ];
                                Db::table('up_u_user')->where('user_id', $up_up_user['user_id'])->update($up_up_user_yj);
                            }
                        }
                    }
                }
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '审核成功']);
        }catch(\Exception $e){
            Db::rollback();
            return json(['code' => 100, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 审核拒绝
     * @return mixed|\think\response\Json
     */
    public function withRefuse(){
        $withdraw_id = input('withdraw_id');
        if(Request::instance()->isPost()){
            $withdraw_remark = input('withdraw_remark');
            if($withdraw_remark == ''){
                $withdraw_remark = '提现退回';
            }
            $withdraw = Db::table('up_withdraw')
                ->where('withdraw_id', $withdraw_id)
                ->field('withdraw_price, withdraw_user_id, withdraw_type, withdraw_inte_id')
                ->find();
            // 如果是提现，则需要考虑已转货款部分
            if($withdraw['withdraw_type'] == 1){
                $huokuan_number = Db::table('up_integral_tixian_hk')
                    ->where('zhuan_inte_id', $withdraw['withdraw_inte_id'])
                    ->sum('zhuan_number');
                $withdraw['withdraw_price'] = $withdraw['withdraw_price'] - $huokuan_number;
            }
            
            $update = [
                'withdraw_status' => 3,
                'withdraw_remark' => $withdraw_remark,
                'withdraw_check_time' => date('Y-m-d H:i:s')
            ];
            Db::startTrans();
            try{
                // 更新申请状态
                Db::table('up_withdraw')->where('withdraw_id', $withdraw_id)->update($update);
                
                // 插入积分明细
                $user = Db::table('up_u_user')->where('user_id', $withdraw['withdraw_user_id'])->field('user_fy_balance')->find();
                $integral = [
                    'inte_user_id' => $withdraw['withdraw_user_id'],
                    'inte_other_user_id' => 0,
                    'inte_type' => 4,
                    'inte_des' => '提现退回-' . $withdraw_remark,
                    'inte_number' => $withdraw['withdraw_price'],
                    'inte_front' => $user['user_fy_balance'],
                    'inte_after' => $user['user_fy_balance'] + $withdraw['withdraw_price'],
                    'inte_time' => date('Y-m-d H:i:s'),
                    'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT)
                ];
                Db::table('up_integral')->insert($integral);
                // 退款到佣金积分
                Db::table('up_u_user')->where('user_id', $withdraw['withdraw_user_id'])->setInc('user_fy_balance', $withdraw['withdraw_price']);
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        return $this->fetch('withdraw/withrefuse', ['withdraw_id' => $withdraw_id]);
    }
    
    /**
     * 提现转货款列表
     * @return mixed|\think\response\Json
     */
    public function withdrawToHuo(){
        if(request()->isAjax()){
            $withdraw = Db::table('up_withdraw')->where('withdraw_id', session('withdraw_id'))->field('withdraw_inte_id')->find();
            $where['zhuan_inte_id'] = $withdraw['withdraw_inte_id'];
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_integral_tixian_hk')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_integral_tixian_hk')
                ->field('zhuan_id, zhuan_number, zhuan_time')
                ->where($where)
                ->order('zhuan_time desc')
                ->page($Nowpage,$limits)
                ->select();
            
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $withdraw_id = input('withdraw_id');
        if(isset($withdraw_id) && $withdraw_id != '') session('withdraw_id', $withdraw_id);
        $withdraw_status = Db::table('up_withdraw')->where('withdraw_id', $withdraw_id)->value('withdraw_status');
        return $this->fetch('withdraw/withdrawtohuo', ['status' => $withdraw_status]);
    }
    
    /**
     * 提现转货款
     * @return mixed|\think\response\Json
     */
    public function huoAdd(){
        $param = input('');
        if(isset($param['inte_id'])){
            $inte_id = $param['inte_id'];
        }else{
            $inte_id = Db::table('up_withdraw')->where('withdraw_id', session('withdraw_id'))->value('withdraw_inte_id');
        }
        $inte = Db::table('up_integral')->where('inte_id', $inte_id)->field('inte_number, inte_user_id')->find();
        $count_zhuan_number = Db::table('up_integral_tixian_hk')->where('zhuan_inte_id', $inte_id)->sum('zhuan_number');
    
        if(Request::instance()->isPost()){
            $zhuan_number = $param['zhuan_number'];
            if($zhuan_number + $count_zhuan_number > $inte['inte_number']) return json(['code' => 100, 'msg' => '转货款总积分不能超过提现总积分']);
    
            $insert = [
                'zhuan_inte_id' => $inte_id,
                'zhuan_user_id' => $inte['inte_user_id'],
                'zhuan_number' => $zhuan_number,
                'zhuan_time' => date('Y-m-d H:i:s')
            ];
    
            $user = Db::table('up_u_user')->where('user_id', $inte['inte_user_id'])
                ->field('user_total_balance, user_first_balance, user_recharge_balance, user_invite_other, user_real_name')
                ->find();
            $update_user = [
                'user_total_balance' => $user['user_total_balance'] + $zhuan_number,
                'user_first_balance' => $user['user_first_balance'] + $zhuan_number,
                'user_recharge_balance' => $user['user_recharge_balance'] + $zhuan_number
            ];
            Db::startTrans();
            try{
                // 插入积分明细详情表
                Db::table('up_integral_tixian_hk')->insert($insert);
    
                // 更新用户总积分&货款
                Db::table('up_u_user')->where('user_id', $inte['inte_user_id'])->update($update_user);
    
                // 用户积分明细
                $integral_user = [
                    'inte_user_id' => $inte['inte_user_id'],
                    'inte_other_user_id' => 0,
                    'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT),
                    'inte_type' => 1,
                    'inte_number' => $zhuan_number,
                    'inte_front' => $user['user_recharge_balance'],
                    'inte_after' => $user['user_recharge_balance'] + $zhuan_number,
                    'inte_time' => date('Y-m-d H:i:s'),
                    'inte_sort' => 1,
                    'inte_des' => '提现转货款'
                ];
                Db::table('up_integral')->insert($integral_user);
    
                //****************************  分佣
                // 给上级和上上级分佣
                if($user['user_invite_other']) {
                    // 上级
                    $up_user = Db::table('up_u_user')->where('user_invite', $user['user_invite_other'])
                        ->field('user_id, user_role, user_fy_balance, user_invite_other, user_total_fy_balance')
                        ->find();
                    if($up_user['user_role'] == 3) { // 货款只有富二代上级和富二代上上级有
                        $up_jia_bl = Db::table('up_fy_config')->where('fy_config_id', 2)->value('fy_config_content');
                        $up_yj = $up_jia_bl / 100 * $zhuan_number; // 佣金数
                        // 上级积分明细
                        $intergral_up = [
                            'inte_user_id' => $up_user['user_id'],
                            'inte_other_user_id' => $inte['inte_user_id'],
                            'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT),
                            'inte_number' => $up_yj,
                            'inte_front' => $up_user['user_fy_balance'],
                            'inte_after' => $up_user['user_fy_balance'] + $up_yj,
                            'inte_time' => date('Y-m-d H:i:s'),
                            'inte_sort' => 2,
                            'inte_type' => 3,
                            'inte_des' => $user['user_real_name'] . '提现转货款-佣金'
                        ];
                        Db::table('up_integral')->insert($intergral_up);
            
                        // 上级佣金积分
                        $up_user_yj = [
                            'user_fy_balance' => $up_user['user_fy_balance'] + $up_yj,
                            'user_total_fy_balance' => $up_user['user_total_fy_balance'] + $up_yj
                        ];
                        Db::table('up_u_user')->where('user_id', $up_user['user_id'])->update($up_user_yj);
            
                        // 上上级
                        if($up_user['user_invite_other']) {
                            $up_up_user = Db::table('up_u_user')->where('user_invite', $up_user['user_invite_other'])
                                ->field('user_id, user_role, user_fy_balance, user_invite_other, user_total_fy_balance')
                                ->find();
                            if($up_up_user['user_role'] == 3) {
                                $up_up_jia_bl = Db::table('up_fy_config')->where('fy_config_id', 4)->value('fy_config_content');
                                $up_up_yj = $up_up_jia_bl / 100 * $zhuan_number; // 佣金数
                                // 上上级积分明细
                                $intergral_up_up = [
                                    'inte_user_id' => $up_up_user['user_id'],
                                    'inte_other_user_id' => $inte['inte_user_id'],
                                    'inte_num' => date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT),
                                    'inte_number' => $up_up_yj,
                                    'inte_front' => $up_up_user['user_fy_balance'],
                                    'inte_after' => $up_up_user['user_fy_balance'] + $up_up_yj,
                                    'inte_time' => date('Y-m-d H"i:s'),
                                    'inte_sort' => 3,
                                    'inte_type' => 3,
                                    'inte_des' => $user['user_real_name'] . '提现转货款-佣金'
                                ];
                                Db::table('up_integral')->insert($intergral_up_up);
                    
                                // 上上级佣金积分
                                $up_up_user_yj = [
                                    'user_fy_balance' => $up_up_user['user_fy_balance'] + $up_up_yj,
                                    'user_total_fy_balance' => $up_up_user['user_total_fy_balance'] + $up_up_yj
                                ];
                                Db::table('up_u_user')->where('user_id', $up_up_user['user_id'])->update($up_up_user_yj);
                            }
                        }
                    }
                }
                
                Db::commit();
                return json(['code' => 200, 'msg' => '转货款成功']);
            }catch(\Exception $e){
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        $can_zhuan = $inte['inte_number'] - $count_zhuan_number;
        return $this->fetch('withdraw/huoadd', ['can_zhuan' => $can_zhuan, 'inte_id' => $inte_id]);
    }
    
    /**
     * 导出Excel
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $withdraw_ids = input('ids');
        if($withdraw_ids == '') return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
    
        $lists = Db::table('up_withdraw')
            ->join('up_u_user', 'withdraw_user_id = user_id', 'LEFT')
            ->field('withdraw_id, withdraw_status, withdraw_type, withdraw_number, withdraw_price, withdraw_remark, 
                withdraw_time, user_real_name, user_phone, user_bank_username, user_bank_name, user_bankcard_code, 
                withdraw_check_time')
            ->where('withdraw_id', 'IN', $withdraw_ids)
            ->order('withdraw_time desc')
            ->select();
        
        foreach($lists as $k => $v){
            // 申请状态
            if($v['withdraw_status'] == 1){
                $lists[$k]['withdraw_status'] = '待审核';
            }elseif($v['withdraw_status'] == 2){
                $lists[$k]['withdraw_status'] = '审核通过';
            }else{
                $lists[$k]['withdraw_status'] = '审核拒绝';
            }
            // 申请种类
            $lists[$k]['withdraw_type'] = $v['withdraw_type'] == 1 ? '提现到银行卡' : '转货款';
            // 订单号
            $lists[$k]['withdraw_number'] = "\t" . $v['withdraw_number'] . "\t";
            // 价格
            $lists[$k]['withdraw_price'] = "\t" . $v['withdraw_price'] . "\t";
            // 手机号
            $lists[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
            // 银行卡号
            $lists[$k]['user_bankcard_code'] = "\t" . $v['user_bankcard_code'] . "\t";
        }
        $cellname = [
            ['user_real_name', '提现用户', 10, 'LEFT'],
            ['user_phone', '提现用户手机号', 20, 'LEFT'],
            ['withdraw_number', '提现单号', 25, 'LEFT'],
            ['withdraw_price', '提现金额', 20, 'LEFT'],
            ['withdraw_status', '提现状态', 20, 'LEFT'],
            ['withdraw_type', '提现类型', 20, 'LEFT'],
            ['user_bank_username', '银行账户名', 20, 'LEFT'],
            ['user_bank_name', '开户行', 20, 'LEFT'],
            ['user_bankcard_code', '卡号', 25, 'LEFT'],
            ['withdraw_remark', '备注', 20, 'LEFT'],
            ['withdraw_time', '申请时间', 20, 'LEFT'],
            ['withdraw_check_time', '审核时间', 20, 'LEFT']
        ];
        $res = exportExcelZhy('提现', 'Withdraw', $cellname, $lists);
        return json($res);
    }
}